<template>
  <div class="page">
    <main-card :title="detailData?.name" :show-screen-space="false" :crumbs="crumbs">
      <template #tool-btn>
        <div class="flex gap-x-8">
          <a-button
            type="default"
            style="width: 36px"
            class="icon-only-btn"
            @click="taskListDrawerStore.changeTaskListOptions({ open: true })"
          >
            <i class="iconfont icon-tasklist-line"></i
          ></a-button>
          <!-- <a-dropdown placement="bottom"> -->
          <a-dropdown placement="bottom" :disabled="detailData?.status !== 4">
            <a-button type="primary" class="icon-with-btn">
              导出
              <i class="iconfont icon-arrow-down-s-line"></i>
            </a-button>
            <template #overlay>
              <a-menu>
                <a-menu-item @click="onExport('line')"> 在线导出 </a-menu-item>
                <a-menu-item @click="onExport('local')"> 本地导出 </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
      </template>
      <div class="detail-body">
        <div class="detail-content">
          <a-spin v-if="detailData?.status === 4" :spinning="loading" class="h-100%">
            <!-- <a-spin :spinning="loading" class="h-100%"> -->
            <div class="tab-list">
              <div
                v-if="detailData?.scheme === 1 || detailData?.scheme === 4"
                class="tab-item"
                :class="[detailData?.scheme !== 4 ? 'fontBold' : activeIndex === 0 && 'active']"
                @click="changeTab(0)"
              >
                去近似（{{ detailData?.approximateCount > 9999 ? '9999+' : detailData?.approximateCount }}）
              </div>
              <div
                v-if="detailData?.scheme === 2 || detailData?.scheme === 4"
                class="tab-item"
                :class="[detailData?.scheme !== 4 ? 'fontBold' : activeIndex === 1 && 'active']"
                @click="changeTab(1)"
              >
                去模糊（{{ detailData?.definitionCount > 9999 ? '9999+' : detailData?.definitionCount }}）
              </div>
            </div>
            <component :is="compMap[activeIndex]" :detail-info="detailData" @updateData="getData" />
          </a-spin>
          <running-status v-else :status="detailData?.status" />
        </div>
        <detail-info :detail-data="detailData" :loading="loading" />
      </div>
    </main-card>
  </div>
  <line-export ref="lineExportRef" v-model:show="showLineExport" :loading="okBtnLoading" @submit="onLineExportSubmit" />

  <task-list-drawer />
</template>

<script setup lang="ts">
  import { message } from 'ant-design-vue'
  import { onUnmounted, ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRoute } from 'vue-router'

  import LineExport from '@/components/LineExport/index.vue'
  import manualMessage from '@/components/ManualMessage/index'
  import useSetInterval from '@/hooks/useSetInterval'
  import { dataCleaningApi } from '@/services/api'

  import Approximation from '../components/Approximation.vue'
  import Deblurring from '../components/Deblurring.vue'
  import DetailInfo from '../components/DetailInfo.vue'
  import RunningStatus from '../components/RunningStatus.vue'
  import TaskListDrawer from '../components/TaskListDrawer/index.vue'
  import { useTaskListDrawerStore } from '../components/TaskListDrawer/store'

  const route = useRoute()
  const parentParams = route.params as any

  const crumbs = [{ name: '数据清洗', path: '/data-clean/list' }, { name: '任务详情' }]

  const compMap = [Approximation, Deblurring]

  const activeIndex = ref(0)
  const changeTab = (index: number) => {
    activeIndex.value = index
  }

  const taskListDrawerStore = useTaskListDrawerStore()

  /* 导出 */
  const showLineExport = ref(false)
  const lineExportRef = ref<InstanceType<typeof LineExport>>()
  const onExport = (type: 'line' | 'local') => {
    if (type === 'line') {
      showLineExport.value = true
      lineExportRef.value?.setFormState({
        name: detailData.value?.name
      })
    } else {
      localExport()
    }
  }
  // 在线导出
  const { loading: okBtnLoading, runAsync: runOnlineExport } = useRequest(dataCleaningApi.onlineExport)
  const onLineExportSubmit = async (formState: any) => {
    await runOnlineExport({ taskId: detailData.value.id, bucketName: formState.name, bucketId: formState.value })
    showLineExport.value = false
    taskListDrawerStore.changeTaskListOptions({ open: true, key: '1' })
  }

  // 本地导出
  const localExport = async () => {
    manualMessage.loading('数据准备中,请耐心等待...', 0)
    try {
      await dataCleaningApi.localExport({ taskId: detailData.value.id })
      taskListDrawerStore.changeTaskListOptions({ open: true, key: '2' })
      message.destroy()
    } catch (error: any) {
      message.destroy()
      message.error(error?.message)
    }
  }

  /* 获取数据 */
  const { start: runDetData, clear: stop } = useSetInterval()
  const { data: detailData, loading, runAsync: runGetData } = useRequest<any>(dataCleaningApi.detail)
  const getData = async (callback?: Function) => {
    const { data } = await runGetData({}, { urlParams: { id: parentParams.id } })
    detailData.value = data
    callback?.()
    ;[2, 4, 5, 6].includes(data?.status) && stop()
  }

  const getDataCallback = () => {
    activeIndex.value = detailData.value?.scheme === 1 || detailData.value?.scheme === 4 ? 0 : 1
  }

  runDetData(() => getData(getDataCallback), 1000 * 5, true)
  onUnmounted(() => {
    stop()
  })
</script>

<style lang="less" scoped>
  .page {
    width: 100%;
  }

  .detail-body {
    display: flex;
    height: 698px;
    background: #fff;
    border: 1px solid #e8e9eb;
    border-radius: 10px;

    .detail-content {
      flex: 1;
      padding: 20px 0;

      .tab-list {
        display: flex;
        gap: 0 40px;
        padding: 0 24px;
        margin-bottom: 17px;

        .tab-item {
          font-size: 16px;
          line-height: 24px;
          color: rgba(25, 25, 48, 0.75);
          font-weight: 400;
          cursor: pointer;

          &.active {
            color: rgba(16, 16, 20, 0.95);
            font-weight: 500;

            &::after {
              display: block;
              margin-top: 8px;
              width: 100%;
              height: 3px;
              background: #1868e9;
              content: '';
            }
          }

          &.fontBold {
            color: rgba(16, 16, 20, 0.95);
            font-weight: 500;
            pointer-events: none;
          }
        }
      }

      :deep(.ant-spin) {
        max-height: 100%;
      }
    }
  }
</style>
